import axios from 'axios';
import service from "./request";
// import env from '../../config/dev.env';
let env = 'development'
import Cookies from 'js-cookie';

let util = {};

const ajaxUrl = env === 'development'
  ? 'http://127.0.0.1:8888'
  : env === 'production'
    ? 'https://www.url.com'
    : 'https://debug.url.com';

util.ajax = axios.create({
  baseURL: ajaxUrl,
  timeout: 30000
});

util.encode = function (key, eles) {
  var keyVal = parseInt(key)
  var arr = []
  for (var i = 0; i < eles.length; ++i) {
    var ele = eles[i]
    arr.push(ele.length ^ keyVal)
    for (var j = 0; j < ele.length; ++j) {
      arr.push(ele[j].charCodeAt(0) ^ keyVal)
    }
  }
  arr.push(keyVal)
  var context = "CV16" + arr.join("%")
  return context;
};

export const exportFile = (url, data = "", name) => {
  if (data) {
    for (let item in data) {
      if (item && !data[item]) {
        data[item] = ""
      }
    }
  }
  axios({
    method: "post",
    url: url,
    withCredentials: true,
    responseType: "blob",
    data: data,
    headers: {
      "request-type": "wap",
      "Authorization": sessionStorage.getItem('credentials'),
      "useragentcode": sessionStorage.getItem('useragentcode')
    },
  }).then((res) => {
    console.log(res, "res")
    const fileName = decodeURI( // 获取文件名
      res.headers['content-disposition'].split('=')[1]
    )

    // Blob 对象表示一个不可变、原始数据的类文件对象（File 接口都是基于Blob）
    const BLOB = res.data
    // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
    const fileReader = new FileReader()
    // 开始读取指定的Blob中的内容。读取完成result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容

    if (BLOB) { // 此处判断是否有数据，也可以在此判断文件类型是否符合
      fileReader.readAsDataURL(BLOB)
    }

    // 处理load事件，该事件在读取操作完成时触发
    fileReader.onload = (event) => {
      let a = document.createElement('a')
      // a.download = `${name}.xls` // 自定义文件名
      a.download = fileName || "aaa" // 使用默认的文件名
      a.href = event.target.result
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  })



}

export const visitFile = (url, data = "", name) => {
  if (data) {
    for (let item in data) {
      if (item && !data[item]) {
        data[item] = ""
      }
    }
  }
  axios({
    method: "post",
    url: url,
    withCredentials: true,
    responseType: "blob",
    data: data,
    headers: {
      "request-type": "wap",
      "Authorization": sessionStorage.getItem('credentials'),
      "useragentcode": sessionStorage.getItem('useragentcode')
    },
  }).then((res) => {
    if (res.data) {
      let responseData = res.data;
      if (responseData != null) {
        let pdfUrl = window.URL.createObjectURL(new Blob([responseData], { type: "application/pdf" }));
        window.open(pdfUrl)
      }
    }
  })



}
util.inOf = function (arr, targetArr) {
  let res = true;
  arr.map(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

util.oneOf = function (ele, targetArr) {
  if (targetArr.indexOf(ele) >= 0) {
    return true;
  } else {
    return false;
  }
};

util.showThisRoute = function (itAccess, currentAccess) {
  if (typeof itAccess === 'object') {
    return util.oneOf(currentAccess, itAccess);
  } else {
    return itAccess === currentAccess;
  }
};

util.getPathObjByName = function (vm, name) {
  let pathObj = vm.$store.state.routers.filter((item) => {
    if (item.children.length <= 1) {
      return item.name === name;
    } else {
      let i = 0;
      let childArr = item.children;
      let len = childArr.length;
      while (i < len) {
        if (childArr[i].name === name) {
          return true;
        }
        i++;
      }
      return false;
    }
  })[0];
  return pathObj;
};

util.setCurrentPath = function (vm, name) {
  let title = '';
  vm.$store.state.routers.forEach(item => {
    if (item.children.length === 1) {
      if (item.children[0].name === name) {
        title = item.title;
      }
    } else {
      item.children.forEach(child => {
        if (child.name === name) {
          title = child.title;
        }
      });
    }
  });
  let currentPathArr = [];

  // if (name === 'home_index') {
  //   currentPathArr = [
  //     {
  //       title: '首页',
  //       path: '',
  //       name: 'home_index'
  //     }
  //   ];
  // } else {
  //   let currentPathObj = vm.$store.state.routers.filter(item => {
  //     if (item.children.length <= 1) {
  //       return false;
  //     } else {
  //       let i = 0;
  //       let childArr = item.children;
  //       let len = childArr.length;
  //       while (i < len) {
  //         if (childArr[i].name === name) {
  //           return true;
  //         }
  //         i++;
  //       }
  //       return false;
  //     }
  //   })[0];
  //   if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
  //     currentPathArr = [
  //       {
  //         title: '首页',
  //         path: '',
  //         name: 'home_index'
  //       }
  //     ];
  //   } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
  //     currentPathArr = [
  //       {
  //         title: currentPathObj.title,
  //         path: '',
  //         name: name
  //       }
  //     ];
  //   } else {
  //     let childObj = currentPathObj.children.filter((child) => {
  //       return child.name === name;
  //     })[0];
  //     currentPathArr = [
  //       {
  //         title: currentPathObj.title,
  //         path: '',
  //         name: currentPathObj.name
  //       },
  //       {
  //         title: childObj.title,
  //         path: currentPathObj.path + '/' + childObj.path,
  //         name: name
  //       }
  //     ];
  //   }
  // }
  vm.$store.commit('setCurrentPath', currentPathArr);

  return currentPathArr;
};

util.openPage = function (vm, name, title) {
  vm.$router.push({
    name: name
  });
  let hasOpened = false;
  vm.pageTagsList.forEach((item, index) => {
    if (item.name === name) {
      hasOpened = true;
      vm.$store.commit('moveToSecond', index);
    }
  });
  if (!hasOpened) {
    vm.$store.commit('inCreateTag', { name: name, title: title });
  }
};
String.prototype.getDate = function () {
  "use strict";
  let strArr = this.split('-');
  let date = new Date(strArr[0], strArr[1] - 1, strArr[2]);
  return date;
};
Date.prototype.getYMD = function () {
  let retDate = this.getMonth() + 1 + "-";    // 获取月份。
  retDate += this.getDate();               // 获取日。
  return retDate;                          // 返回日期。
}
util.getDays = function (day1, day2) {
  // 获取入参字符串形式日期的Date型日期
  let d1 = day1.getDate();
  let d2 = day2.getDate();

  // 定义一天的毫秒数
  let dayMilliSeconds = 1000 * 60 * 60 * 24;

  // 获取输入日期的毫秒数
  let d1Ms = d1.getTime();
  let d2Ms = d2.getTime();

  // 定义返回值
  let ret;

  // 对日期毫秒数进行循环比较，直到d1Ms 大于等于 d2Ms 时退出循环
  // 每次循环结束，给d1Ms 增加一天
  for (d1Ms; d1Ms <= d2Ms; d1Ms += dayMilliSeconds) {

    // 如果ret为空，则无需添加","作为分隔符
    if (!ret) {
      // 将给的毫秒数转换为Date日期
      let day = new Date(d1Ms);

      // 获取其年月日形式的字符串
      ret = day.getYMD();
    } else {

      // 否则，给ret的每个字符日期间添加","作为分隔符
      let day = new Date(d1Ms);
      ret = ret + ',' + day.getYMD();
    }
  }
  let array = ret.split(",");
  return array;
};

util.formatDate = function (d, type) {
  if (d) {
    let date = new Date(d);
    let yy = date.getFullYear();      //年
    let mm = date.getMonth() + 1;     //月
    let dd = date.getDate();
    let hh = date.getHours();
    let min = date.getMinutes();
    let clock = '';
    if (type === 'YY-MM-DD') {
      clock += yy + '-';
      if (mm < 10) {
        clock += "0";
      }
      clock += mm + "-";
      if (dd < 10) {
        clock += "0";
      }                                 //日
      clock += dd
    } else if (type === 'DD-MM-YY') {
      if (dd < 10) {
        clock += "0";
      }                                 //日
      clock = dd + "-";
      if (mm < 10) {
        clock += "0";
      }
      clock += mm + "-";
      clock += yy;
    } else if (type === 'YY-MM-DD HH-MM') {
      clock += yy + '-';
      if (mm < 10) {
        clock += "0";
      }
      clock += mm + "-";
      if (dd < 10) {
        clock += "0";
      }
      clock += dd + ' ';
      if (hh < 10) {
        clock += " 0";
      }
      clock += hh + ":";
      if (min < 10) {
        clock += "0";
      }
      clock += min
    }
    return clock
  } else {
    return "暂无"
  }
};

util.cloneObj = function (obj) {
  let newObj = {};
  if (obj instanceof Array) {
    newObj = [];
  }
  for (let key in obj) {
    let val = obj[key];
    //newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; //arguments.callee 在哪一个函数中运行，它就代表哪个函数, 一般用在匿名函数中。
    newObj[key] = typeof val === 'object' ? util.cloneObj(val) : val;
  }
  return newObj;
};

util.sliceSomeSizeArray = function (a, s) {
  let l = a.length;
  let array = [];
  for (let i = 0; i < l; i += s) {
    array.push(a.slice(i, i + s))
  }
  return array
};

util.sortNumber = function (a, b) {
  return a - b
};

util.pathToParam = function (pa, jsonObj, flag) {
  var f = true;
  for (var i in jsonObj) {
    if (jsonObj[i] !== '') {
      f = false;
      pa += "&" + i + "=" + jsonObj[i];
    }
  }
  if (!f) {
    if (flag) {
      pa = pa.replace(/&/, "?");
    }
    return pa;
  } else {
    return pa;
  }
};

util.consoleString = function () {
  console.log('woshijswenjin')
}

// 将时间转化为ISO格式
util.dateToISOString = function (time) {
  if (time) {
    let date1 = new Date(time).toJSON();
    return new Date(
      +new Date(date1) + 8 * 3600 * 1000
    ).toISOString();
  } else {
    return null
  }
}

// 判断对象属性是否全为空,全为空return true
util.formNullValidate = function (params) {
  for (let key in params) {
    // 不能判断数组第一个空、第二个有值的情况
    if (params[key] == null || params[key] == "" || params[key].length == 0 || params[key][0] == "") {
    } else {
      return false; // 终止程序
    }
  }

  return true;
}

// 获取地址栏的url
util.GetRequest = function (params) {
  //url例子：www.bicycle.com?id="123456"&Name="bicycle"；  
  // var url = decodeURI(location.hash); //?id="123456"&Name="bicycle";
  var url = params; //?id="123456"&Name="bicycle";
  var object = {};
  if (url.indexOf("?") != -1)//url中存在问号，也就说有参数。  
  {
    var str = url.substr(1);  //得到?后面的字符串
    var str1 = str.split("?");
    var strs = str1[1].split("&");  //将得到的参数分隔成数组[id="123456",Name="bicycle"];
    for (var i = 0; i < strs.length; i++) {
      object[strs[i].split("=")[0]] = strs[i].split("=")[1]
    }
  }
  return object;
}

export const throttle = (fn, delay = 1000) => {
  let timer
  return function () {
    let arg = arguments;
    if (!timer) {
      timer = true;
      fn && fn.apply(this, arg);
      setTimeout(() => {
        timer = false;
      }, delay)
    }
  }
}

export default util;
